package com.polly.esphwevent.common.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author liqin@nd.com.cn
 * @version V1.0
 * @title: HttpUtils
 * @description: TODO(用一句话描述该文件做什么)
 * @date: 2019/2/25 17:57
 */
@Slf4j
public class HttpUtils {

    //响应的ContentType内容
    private static final String RESPONSE_CONTENT_TYPE = "application/json";

    //响应编码
    private static final String RESPONSE_CHARACTER_ENCODING = "utf-8";

    void setJsonResponse(HttpServletResponse response,Object data) throws IOException{
        response.setCharacterEncoding(RESPONSE_CHARACTER_ENCODING);
        response.setContentType(RESPONSE_CONTENT_TYPE);
        response.getOutputStream().write(JSON.toJSONBytes(data));
    }

    //exposeErrorRequestAttributes

    public static void writeResponse(HttpStatus httpStatus, String content, HttpServletResponse response){
        PrintWriter printWriter = null;
        try {
            response.setCharacterEncoding(RESPONSE_CHARACTER_ENCODING);
            response.setContentType(RESPONSE_CONTENT_TYPE);
            response.setStatus(httpStatus.value());
            printWriter = response.getWriter();
            printWriter.write(content);
            printWriter.flush();
        } catch (Exception e) {
            log.error("write response body failed.causes by:"+e.getLocalizedMessage(), e);
        } finally {
            IOUtils.closeQuietly(printWriter);
        }
    }

}
